import { ref, reactive } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { handleParams } from '@/utils/common'

// 列表 | 分页 | 搜索 | 多选 | 删除 | 批量删除
export function useInitTable(option = {}) {
  // 搜索参数
  const params = reactive({ ...option.params })

  // 表格参数
  const tableData = ref([])
  const tableLoading = ref(false)

  // 分页参数
  const total = ref(0)

  // 获取数据
  async function getData() {
    tableLoading.value = true
    try {
      const result = await option.getDataAPI(handleParams(params))
      // 是否需要处理响应结果
      if (option.onSuccess && typeof option.onSuccess === 'function') {
        option.onSuccess(result)
      } else {
        // 默认处理
        tableData.value = result.rows
        total.value = result.count
      }
    } finally {
      tableLoading.value = false
    }
  }
  getData()

  // 页面条数发生改变
  // function handleSizeChange(size) {
  //   searchForm.pageSize = size
  //   getData()
  // }
  // 搜索
  function handleSearch() {
    params.page = 1
    getData()
  }

  // 多选
  const multiSelection = ref([])
  function handleSelectionChange(selection) {
    multiSelection.value = selection
  }

  // 批量删除
  async function handleBatchDelete() {
    if (multiSelection.value.length === 0) return ElMessage.error('请先选择数据')
    await ElMessageBox.confirm('确定要删除选中的数据吗?', '温馨提示', { type: 'warning' })
    tableLoading.value = true
    try {
      // 整理参数
      const ids = multiSelection.value.map((item) => item.id).join(',')
      await option.deleteAPI(ids)
      ElMessage.success('删除成功')
      multiSelection.value = []
      getData()
    } finally {
      tableLoading.value = false
    }
  }

  // 删除
  async function handleDelete(row) {
    row.btnLoading = true
    try {
      await option.deleteAPI(row.id)
      ElMessage.success('删除成功')
      getData()
    } finally {
      row.btnLoading = false
    }
  }

  // 计算序号
  const handleIndex = (index) => {
    return (params.page - 1) * params.pageSize + index + 1
  }

  return {
    params,
    tableData,
    tableLoading,
    total,
    multiSelection,
    handleSearch,
    getData,
    handleSelectionChange,
    handleBatchDelete,
    handleDelete,
    handleIndex
  }
}
